// pages/index/oneButtonSleep/onbuttonsleep.js
import * as echarts from '../../../ec-canvas/echarts'
const utils = require("../../../utils/util")
const app = getApp()
const network = require('../../../utils/network')
const bluetoothUtils = require("../../../utils/bluetoothUtils")
const api = require('../../../utils/api')
let timer = null
let timer2 = null
Page({

  /**
   * 页面的初始数据
   */
  data: {
    ec_5: {
      lazyLoad: true
    },
    explain1: '深度放松 释放压力 快速入眠',
    explain2: '助眠过程中操作遥控器任意按钮都会打断一键入眠',
    time: 0,
    level: 1,
    functionFlag: false,
    title1: '',
    text1: '',
    text12: '',
    title2: '',
    text2: '',
    title3: '',
    text31: '',
    text32: '',
    text33: '',
    fixedExplainFlag: false,
    fixStartFlag: false,
    img123Src: '',
    levelTitle: '',
    heartRate: '--',
    breathRate: '--',
    hr: [],
    br: [],
    HBindex: 1,
    musicClassName: '虫鸣',
    musicName: '02.夏虫',
    musicTimeNow: '00:00',
    musicTimeLong: '09:30',
    noData: true,
    count: 0, // 设置 计数器 初始为0
    countTimer: null, // 设置 定时器 初始为null
    showProgress: false,
    deviceID: null, //设备ID
    bluetoothNumber: '',
    wifiboxNumber: '',
    familyId: 0,
    showEcharts: true,
    songBtn: '/images/experience/startMusic.png',
    songBackground: 'https://ks-experience-system.oss-cn-hangzhou.aliyuncs.com/softide/version_2/experience/mainRain.png',
    reportSuccessFlag: false,
    bluetoothInfo: null, //记录蓝牙的基本信息
    setHR: [],
    setBR: [],
    reconnectionTimes: 0,
    goMusic: false,
    ifConnect: true,
    stressData: '',
    listener: null,
    dialogShow2: false,
    msgtext: '由于离床过多、网络等问题，未生成一键入眠体验报告',
    listener: null
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.setData({
      bluetoothNumber: options.bluetoothname,
      wifiboxNumber: options.wifiboxNumber,
      familyId: options.familyId
    })
    this.drawProgressbg();
    // this.getmusic()
    // this.countInterval()
  },
  //时序比较处理
  time(time1) {
    let _this = this
    timer = setTimeout(() => {
      var myDate = new Date();
      let time = _this.timedifference(time1, myDate.getTime())
      _this.setData({
        time: time
      })
      // wx.setStorageSync('sleepTime', time)
      if (this.data.functionFlag == false || time > 931) {
        _this.setData({
          level: 1,
          time: 0,
          explain1: '深度放松 释放压力 快速入眠',
          explain2: '助眠过程中操作遥控器任意按钮都会打断一键入眠',
          functionFlag: false
        })
        _this.drawProgressCircle(0);
      } else if (time > 0 && time <= 25 && _this.data.explain2 != '零重力减压，太空失重体验，释放身体压力') {
        _this.setData({
          level: 1,
          explain1: '全身舒展中',
          explain2: '零重力减压，太空失重体验，释放身体压力',
        })
        _this.time(time1)
        _this.drawProgressCircle(time / 931);
      } else if (time > 25 && time <= 80 && _this.data.explain2 != '零重力按摩，头部深度按摩，消除疲劳') {
        _this.setData({
          level: 1,
          explain1: '全身舒展中',
          explain2: '零重力按摩，头部深度按摩，消除疲劳',
        })
        _this.time(time1)
        _this.drawProgressCircle(time / 931);
      } else if (time > 80 && time <= 146 && _this.data.explain2 != '摇摆哄睡，全身舒展') {
        _this.setData({
          level: 1,
          explain1: '全身舒展中',
          explain2: '摇摆哄睡，全身舒展',
        })
        _this.time(time1)
        _this.drawProgressCircle(time / 931);
      } else if (time > 146 && time <= 326 && _this.data.explain2 != '振动按摩，全身按摩减压') {
        _this.setData({
          level: 2,
          explain1: '全身放松中',
          explain2: '振动按摩，全身按摩减压',
        })
        _this.time(time1)
        _this.drawProgressCircle(time / 931);
      } else if (time > 326 && time <= 481 && _this.data.explain2 != '促进呼吸，足部放松') {
        _this.setData({
          level: 2,
          explain1: '全身放松中',
          explain2: '促进呼吸，足部放松',
        })
        _this.time(time1)
        _this.drawProgressCircle(time / 931);
      } else if (time > 481 && time <= 676 && _this.data.explain2 != '零重力拉伸，全身放松') {
        _this.setData({
          level: 3,
          explain1: '体位入眠中',
          explain2: '零重力拉伸，全身放松',
        })
        _this.time(time1)
        _this.drawProgressCircle(time / 931);
      } else if (time > 676 && time <= 876 && _this.data.explain2 != '促进呼吸，体位入眠') {
        _this.setData({
          level: 3,
          explain1: '体位入眠中',
          explain2: '促进呼吸，体位入眠',
        })
        _this.time(time1)
        _this.drawProgressCircle(time / 931);
      } else if (time > 876 && time <= 931 && _this.data.explain2 != '晚安好梦') {
        _this.setData({
          level: 3,
          explain1: '体位入眠中',
          explain2: '晚安好梦',
        })
        _this.time(time1)
        _this.drawProgressCircle(time / 931);
      } else {
        _this.time(time1)
        _this.drawProgressCircle(time / 931);
      }
    }, 10000);
  },
  //计算两个时间之间的时间差
  timedifference: function (faultDate, completeTime) {
    var stime = Date.parse(new Date(faultDate)); //获得开始时间的毫秒数
    var etime = Date.parse(new Date(completeTime)); //获得结束时间的毫秒数
    var usedTime = etime - stime; //两个时间戳相差的毫秒数
    var days = Math.floor(usedTime / (24 * 3600 * 1000));
    //计算出小时数
    var leave1 = usedTime % (24 * 3600 * 1000); //计算天数后剩余的毫秒数
    var hours = Math.floor(leave1 / (3600 * 1000)); //将剩余的毫秒数转化成小时数
    //计算相差分钟数
    var leave2 = leave1 % (3600 * 1000); //计算小时数后剩余的毫秒数
    var minutes = Math.floor(leave2 / (60 * 1000)); //将剩余的毫秒数转化成分钟
    //计算相差秒数
    var leave3 = leave2 % (60 * 1000); //计算分钟数后剩余的毫秒数
    var seconds = Math.floor(leave3 / 1000); //将剩余的毫秒数转化成秒数
    var dayStr = days == 0 ? "" : days + "d:";
    var hoursStr = hours == 0 ? "" : hours + "h:";
    var minutesStr = minutes == 0 ? "" : minutes;
    var time = minutesStr * 60 + seconds;
    // console.log(time)
    if (time > 931) {
      this.setReport(faultDate)
    }
    return time;
  },

  setReport: async function (faultDate) {
    const _this = this
    var time = new Date(faultDate)
    var start = new Date(faultDate + 180 * 1000)
    var end = new Date(faultDate + 480 * 1000)
    let startTime = this.initTime(time)
    let timeStart = this.initTime(start)
    let timeEnd = this.initTime(end)
    console.log('setHR', this.data.setHR)
    console.log('setBR', this.data.setBR)
    console.log('starttime', startTime)
    let data = {
      breath_rate_stage: this.data.setBR.toString().substr(0, this.data.setBR.toString().length).substr(0),
      heart_rate_stage: this.data.setHR.toString().substr(0, this.data.setHR.toString().length).substr(0),
      start_date: startTime
    }
    console.log('breath_rate_stage', data.breath_rate_stage)

    if (app.globalData.dataswitch == true) {
      if (this.data.setBR.length > 30 && this.data.setHR.length > 30) {
        bluetoothUtils.myShowLoading('报告计算中')
        api.oneSleepReport(data, app.globalData.token).then(res => {
          // if (res.data.code == 200) {
          console.log('stressreport', res.data)
          _this.data.stressData = JSON.stringify(res.data.data)
          bluetoothUtils.myHideLoading()
          _this.setData({
            reportSuccessFlag: true
          })
          // }
        })
      } else {
        bluetoothUtils.myHideLoading()
        _this.setData({
          msgtext: '由于离床过多、网络等问题，未生成一键入眠体验报告',
          dialogShow2: true
        })

      }
    } else {
      _this.setData({
        msgtext: '我的->数据开关，开启后可生成一键入眠专属体验报告',
        dialogShow2: true
      })
    }
    app.globalData.BRDATA = null
    app.globalData.HRDATA = null
    app.globalData.setBR = null
    app.globalData.setHR = null
    wx.offBLECharacteristicValueChange(_this.data.listener)
  },

  initTime(faultDate) {
    let time = new Date(faultDate)
    let month = ''
    if (time.getMonth() < 9) {
      month = '0' + (time.getMonth() - 1 + 2)
    } else {
      month = (time.getMonth() - 1 + 2)
    }

    let day = ''
    if (time.getDate() < 10) {
      day = '0' + time.getDate()
    } else {
      day = time.getDate()
    }

    let hour = ''
    if (time.getHours() < 10) {
      hour = '0' + time.getHours()
    } else {
      hour = time.getHours()
    }

    let min = ''
    if (time.getMinutes() < 10) {
      min = '0' + time.getMinutes()
    } else {
      min = time.getMinutes()
    }

    let second = ''
    if (time.getSeconds() < 10) {
      second = '0' + time.getSeconds()
    } else {
      second = time.getSeconds()
    }

    let initTime = time.getFullYear() + '-' + month + '-' + day + ' ' + hour + ':' + min + ':' + second
    return initTime
  },

  start: function () {
    this.setData({
      hr: [60, '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', ''],
      br: [15, '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', ''],
      HBindex: 1,
      time: 1,
      heartRate: '--',
      breathRate: '--'
    })
    this.time2()
    // this.drawProgressCircle(0);
    let _this = this
    this.setData({
      functionFlag: true,
      img123Src: '/images/onebuttonsleep/1.png',
      levelTitle: '全身舒展',
      fixStartFlag: true,
    })
    _this.bedToStop()
    setTimeout(() => {
      _this.setData({
        img123Src: '/images/onebuttonsleep/2.png',
        levelTitle: '全身放松',
      })
      setTimeout(() => {
        _this.setData({
          img123Src: '/images/onebuttonsleep/3.png',
          levelTitle: '体位入眠',
        })
        setTimeout(() => {
          _this.setData({
            img123Src: '/images/onebuttonsleep/1.png',
            levelTitle: '全身舒展',
            fixStartFlag: false,
            time: 1,
            level: 1,
            explain1: '全身舒展中',
            explain2: '零重力减压，太空失重体验，释放身体压力',
            noData: false,
            showProgress: true,
          })
          if (wx.getStorageSync('songFlag') == false) {
            // _this.musicBtn()
          }
          var myDate = new Date();
          wx.setStorageSync('oneManSleep', myDate.getTime())
          wx.setStorageSync('smartRelax', null)
          wx.setStorageSync('remote', null)
          _this.time(myDate.getTime())
          _this.startOneButtonSleep()
          _this.oneComponent = _this.selectComponent('#mychart-dom-bar');
          console.log('oneComponent', _this.oneComponent)
          setTimeout(() => {
            _this.getOption()
          }, 500)
          // _this.drawProgressCircle(myDate.getTime() / 931);
        }, 1000);
      }, 1000);
    }, 1000);
  },

  bingLongTap: function () {
    let _this = this
    this.setData({
      time: 0,
      explain1: '深度放松 释放压力 快速入眠',
      explain2: '助眠过程中操作遥控器任意按钮都会打断一键入眠',
      level: 1,
      functionFlag: false,
      title1: '',
      text1: '',
      text12: '',
      title2: '',
      text2: '',
      title3: '',
      text31: '',
      text32: '',
      text33: '',
      showProgress: false,
      text13: '',
      text14: '',
      text15: '',
      text16: '',
      text22: '',
      text23: '',
      text24: '',
      text34: '',
      text35: '',
    })
    this.setData({
      heartRate: '--',
      breathRate: '--',
      noData: true
    })
    // app.globalData.playmusic.stop()
    clearTimeout(timer)
    clearTimeout(timer2)
    app.globalData.BRDATA = []
    app.globalData.HRDATA = []
    app.globalData.setBR = []
    app.globalData.setHR = []
    wx.offBLECharacteristicValueChange(_this.data.listener)
    _this.drawProgressCircle(0);
    wx.setStorageSync('oneManSleep', null)
    _this.bedToStop()
    setTimeout(() => {
      _this.bedToFlat()
    }, 1500);
    wx.vibrateLong();
  },

  time2() {
    let _this = this
    timer2 = setTimeout(() => {
      // wx.setStorageSync('sleepTime', time)
      if (_this.data.functionFlag != false && _this.data.time < 931 && wx.getStorageSync('remote') != true) {
        _this.getHeartBreath()
        _this.time2()
      }
    }, 10000);
  },
  // buffer转16进制
  ab2hex: function (buffer) {
    let hexArr = Array.prototype.map.call(
      new Uint8Array(buffer),
      function (bit) {
        return ('00' + bit.toString(16)).slice(-2)
      }
    )
    return hexArr.join('');
  },
  getHeartBreath: async function () {
    let _this = this
    let listener = function (characteristic) {
      var realTimeData = _this.ab2hex(characteristic.value)
      // console.log("接受实时数据======>", realTimeData)
      if (realTimeData.substring(0, 4) == 'ffaa' && realTimeData.length > 30) {
        let realData = realTimeData.substring(20, 18) + realTimeData.substring(18, 16) + realTimeData.substring(16, 14) + realTimeData.substring(14, 12)
        // console.log("realData======>", realData)
        let binaryData = utils.hexToBinary(realData)
        // console.log("binaryData====>", binaryData)
        let hr = parseInt(binaryData.substr(-9, 9), 2).toString(10)
        let br = parseInt(binaryData.substr(-16, 7), 2).toString(10)
        let turn = parseInt(binaryData.substr(-32, 4), 2).toString(10)
        let leave = parseInt(binaryData.substr(-18, 2), 2).toString(10)
        let side = parseInt(utils.hexToBinary(realTimeData.substring(5, 6)), 2).toString(10)
        console.log("边", side, "心率", hr, "呼吸", br, "离床", leave, "\n\n")
        if (leave == 0) { //离床 0-在床 1-离床
          if (side == 0) {
            // console.warn('hr', hr, br)
            let a1 = _this.data.hr
            a1.splice(_this.data.HBindex, 1, hr)
            let a2 = _this.data.br
            a2.splice(_this.data.HBindex, 1, br)
            let a3 = _this.data.setHR
            a3.push(parseInt(hr))
            let a4 = _this.data.setBR
            a4.push(parseInt(br))
            _this.setData({
              heartRate: parseInt(hr),
              breathRate: parseInt(br),
              hr: a1,
              br: a2,
              setHR: a3,
              setBR: a4,
              HBindex: _this.data.HBindex + 1
            })
            // console.error('heartRate', _this.data.heartRate, _this.data.breathRate)
            app.globalData.BRDATA = _this.data.br
            app.globalData.HRDATA = _this.data.hr
            app.globalData.setBR = a4
            app.globalData.setHR = a3
          }
        } else { //离床数据直接清空列表

        }
      }
    }
    // if (app.globalData.realTimeListener == null) {
    //   app.globalData.realTimeListener = listener
    this.setData({
      listener: listener
    })
    wx.onBLECharacteristicValueChange(_this.data.listener)
    // }
    setTimeout(() => {
      _this.getOption()
    }, 500)

    // }
  },

  init_chart: function (br, hr) { //初始化第一个图表
    const _this = this
    _this.oneComponent.init((canvas, width, height, dpr) => {
      const chart = echarts.init(canvas, null, {
        width: width,
        height: height,
        devicePixelRatio: dpr // new
      });
      line_set(chart, br, hr)
      this.chart = chart;
      return chart;
    });
  },
  getOption: function () {
    console.log('br', this.data.br, 'hr', this.data.hr)
    this.init_chart(this.data.br, this.data.hr)
  },

  fixedExplain: function () {
    this.setData({
      fixedExplainFlag: true
    })
    if (this.data.time > 931) {
      this.setData({
        title1: '',
        text1: '',
        text12: '',
        title2: '',
        text2: '',
        title3: '',
        text31: '',
        text32: '',
        text33: '',
        text13: '',
        text14: '',
        text15: '',
        text16: '',
        text22: '',
        text23: '',
        text24: '',
        text34: '',
        text35: '',
      })
    } else if (this.data.time == 0) {
      this.setData({
        title1: '了解一键入眠 ',
        text1: '一键入眠通过智能床独有的适度拉伸运动和振动按摩功能，帮助人体释放压力，深度放松，实现科学助眠。',
        text12: ' 在体验一键入眠的过程中，您会体验到：',
        text13: '1.零重力模式营造出的外太空失重感，结合振动按摩，达到深度按摩的效果，深度释放身体压力，消除疲劳[5]；',
        text14: '2.规律性抬升头部与脚部的摇摆哄睡体验，促进睡眠，提高睡眠质量[1][2]；',
        text15: '3.头部抬起体验，增加血氧饱和度，促进呼吸，提高睡眠效率[3]；',
        text16: '4.零重力拉伸体验，床体规律性运动拉伸全身，起到舒展和放松全身的作用，更好入睡[4]。',
        title2: '一键入眠流程',
        text2: '     保持仰卧姿势（正躺在智能床上）后开启一键入眠，您将会十五分半钟的三段式助眠体验，舒缓焦虑，消除疲劳。',
        text22: '一阶段舒展全身，消除疲劳。智能床开启零重力模式与头部深度按摩，体验太空失重感，消除疲劳。消除疲劳体验后摇摆哄睡，舒展全身。',
        text23: '二阶段放松全身，缓解焦虑。智能床开启头部与脚部振动按摩，全身减压。全身减压后抬起床头，促进呼吸。',
        text24: '三阶段体位助眠，轻松入眠。智能床开启零重力拉伸，放松全身。放松全身后智能床缓缓放平，轻松入眠。',
        title3: '参考资料',
        text31: '[1] Schreiner T, Staresina BP. Sleep: Rock and Swing versus Toss and Turn[J]. Curr Biol. 2019 Feb 4;29(3):R86-R88.',
        text32: ' [2] Baek S, Yu H, Roh J, Lee J, Sohn I, Kim S, Park C. Effect of a Recliner Chair with Rocking Motions on Sleep Efficiency[J]. Sensors (Basel). 2021 Dec 8;21(24):8214. ',
        text33: ' [3] Souza FJFB, Genta PR, de Souza Filho AJ, et al. The influence of head-of-bed elevation in patients with obstructive sleep apnea[J]. Sleep Breath. 2017 ;21(4):815-820. （阻塞性睡眠呼吸暂停患者床头抬高的影响）',
        text34: '   [4] Page P. Current concepts in muscle stretching for exercise and rehabilitation[J]. Int J Sports Phys Ther. 2012 ;7(1):109-119. （肌肉拉伸在运动和康复方面的目前概念.国际运动物理治疗杂志）',
        text35: '  [5] 张冬冬. 按摩椅机械装置的设计与研究[D].浙江工业大学,2015.',
      })
    } else if (this.data.time > 0 && this.data.time <= 25) {
      this.setData({
        title1: '零重力减压',
        text1: '　舒福德通过将智能床人体工程学设计与零重力原理相结合，通过机械结构运动的方式使人体处于中性身体姿势，营造出一种外太空失重感，彻底释放人体压力，给用户带来轻松自然的感受。',
        text12: '',
        title2: '理论依据',
        text2: '　美国太空总署NASA的中性身体姿势（Neutral Body Posture， NBP）研究显示，零重力环境中，人体在自然放松且不施加外力的情况下往往会呈现出特定的姿势：上躯干与大腿之间呈 128° （± 7°），大腿与小腿之间呈 133°（±8°），该姿势对神经、腱、肌肉和骨骼的拉力和压力最小[1][2]。',
        title3: '参考文献：',
        text31: '[1] Tommaso  S,  Irene  L  S.  Chapter  15:  Habitability  and  habitat  design[M].  Space  Safety  and  Human Performance. 2018: 653-719.',
        text32: '[2]Occupational and Environmental Health Center,University of Connecticut. Neutral Posture [EB/OL].http://oehc.uchc.edu/ ergo_neutralposture.asp',
        text33: '',
        text13: '',
        text14: '',
        text15: '',
        text16: '',
        text22: '',
        text23: '',
        text24: '',
        text34: '',
        text35: '',
      })
    } else if (this.data.time > 25 && this.data.time <= 80) {
      this.setData({
        title1: '零重力按摩',
        text1: '　在人体处于零重力状态，也就是人体处于最放松的倾躺状态时，此时的按摩是一种深度按摩状态，按摩效果也是最佳的[1]。 ',
        text12: '',
        title2: '',
        text2: '',
        title3: '理论依据：',
        text31: '[1]张冬冬. 按摩椅机械装置的设计与研究[D].浙江工业大学,2015.',
        text32: '',
        text33: '',
        text13: '',
        text14: '',
        text15: '',
        text16: '',
        text22: '',
        text23: '',
        text24: '',
        text34: '',
        text35: '',
      })
    } else if (this.data.time > 80 && this.data.time <= 146) {
      this.setData({
        title1: '摇摆哄睡',
        text1: '　摇摆运动可以正向增加纺锤体和深度睡眠阶段的持续时间，促进放松和睡眠，从而提高睡眠质量。',
        text12: '',
        title2: '',
        text2: '',
        title3: '参考文献：',
        text31: '[1]Schreiner T, Staresina BP. Sleep: Rock and Swing versus Toss and Turn[J]. Curr Biol. 2019 Feb 4;29(3):R86-R88. ',
        text32: '[2] Baek S, Yu H, Roh J, Lee J, Sohn I, Kim S, Park C. Effect of a Recliner Chair with Rocking Motions on Sleep Efficiency[J]. Sensors (Basel). 2021 Dec 8;21(24):8214. ',
        text33: '[3]Omlin X, Crivelli F, Näf M, et al. The Effect of a Slowly Rocking Bed on Sleep[J]. Sci Rep. 2018 Feb 1;8(1):2156. ',
        text13: '',
        text14: '',
        text15: '',
        text16: '',
        text22: '',
        text23: '',
        text24: '',
        text34: '',
        text35: '',
      })
    } else if (this.data.time > 146 && this.data.time <= 326) {
      this.setData({
        title1: '振动按摩',
        text1: '　振动按摩可减轻运动后的疲劳和肌肉酸痛，促进局部肌肉的血液循环，对缓和肌肉损伤及疲劳恢复有显著效果。通过40Hz特定频率进行按摩，放松全身，改善睡眠状况，减少入睡时长，增加睡眠时间，提高睡眠效率。',
        text12: '',
        title2: '',
        text2: '',
        title3: '参考文献：',
        text31: '[1]Lai YH, Wang AY, Yang CC, et al. The Recovery Benefit on Skin Blood Flow Using Vibrating Foam Rollers for Postexercise Muscle Fatigue in Runners[J]. Int J Environ Res Public Health. 2020 ;17(23):9118.(使用振动泡沫滚轮对皮肤血液流动的恢复益处，用于跑步者锻炼后肌肉疲劳)',
        text32: '[2]宋法明,刘北湘.全身振动介入静态伸展对离心运动后延迟性肌肉酸痛的影响研究[J].山东体育学院学报,2017,33(01):74-79.DOI:10.14104/j.cnki.1006-2076.2017.01.013',
        text33: '[3]朱丽娟,陈勇,吴楚燕.《体感音乐疗法在睡眠障碍患者中的应用研究》 .',
        text13: '',
        text14: '',
        text15: '',
        text16: '',
        text22: '',
        text23: '',
        text24: '',
        text34: '',
        text35: '',
      })
    } else if (this.data.time > 326 && this.data.time <= 481) {
      this.setData({
        title1: '足部按摩',
        text1: '　足部和背部按摩可有效降低原发性高血压和改善睡眠质量[1]。',
        text12: '',
        title2: '头部抬起',
        text2: '　轻度床头抬高可以帮助打开气道，获得更好的气流，增加血氧饱和度，促进呼吸[2]。',
        title3: '理论依据：',
        text31: '[1]rslan G, Ceyhan Ö, Mollaoğlu M. The influence of foot and back massage on blood pressure and sleep quality in females with essential hypertension: a randomized controlled study[J]. J Hum Hypertens. 2021 ;35(7):627-637. (足部和背部按摩对原发性高血压女性血压和睡眠质量的影响：一项随机对照研究)',
        text32: '[2]Souza FJFB, Genta PR, de Souza Filho AJ, et al. The influence of head-of-bed elevation in patients with obstructive sleep apnea[J]. Sleep Breath. 2017 ;21(4):815-820. （阻塞性睡眠呼吸暂停患者床头抬高的影响）',
        text33: '',
        text13: '',
        text14: '',
        text15: '',
        text16: '',
        text22: '',
        text23: '',
        text24: '',
        text34: '',
        text35: '',
      })
    } else if (this.data.time > 481 && this.data.time <= 676) {
      this.setData({
        title1: '零重力拉伸',
        text1: '　模拟拉伸运动，有助于缓解肌肉紧张，缓解下背部疼痛，促进血液循环，起到舒展和放松全身的作用，更好入睡。',
        text12: '',
        title2: '',
        text2: '',
        title3: '参考资料：',
        text31: '[1] Page P. Current concepts in muscle stretching for exercise and rehabilitation[J]. Int J Sports Phys Ther. 2012 ;7(1):109-119. （肌肉拉伸在运动和康复方面的目前概念.国际运动物理治疗杂志）',
        text32: '[2]伸展和加强肌肉锻炼是治疗和预防背痛的关键：https://www.health.harvard.edu/healthbeat/stretching-and-strengthening-are-key-to-healing-and-preventing-back-pain',
        text33: '[3] Kruse NT, Scheuermann BW. Cardiovascular Responses to Skeletal Muscle Stretching: “Stretching” the Truth or a New Exercise Paradigm for  Cardiovascular Medicine? [J] Sports Med. 2017 ;47(12):2507-2520. （骨骼肌拉伸的心血管反应：“拉伸” 是心血管医学的真理还是新运动范式？运动医学 ',
        text13: '',
        text14: '',
        text15: '',
        text16: '',
        text22: '',
        text23: '',
        text24: '',
        text34: '',
        text35: '',
      })
    } else if (this.data.time > 676 && this.data.time <= 876) {
      this.setData({
        title1: '体位入眠',
        text1: '　轻度床头抬高可以帮助打开气道，在无意识时获得更好的气流；',
        text12: '　显著降低了呼吸暂停-低通气指数（AHI），增加血氧饱和度，提高睡眠效率[1]。',
        title2: '',
        text2: '',
        title3: '理论依据：',
        text31: '[1]Souza FJFB, Genta PR, de Souza Filho AJ, et al. The influence of head-of-bed elevation in patients with obstructive sleep apnea[J]. Sleep Breath. 2017 ;21(4):815-820. （阻塞性睡眠呼吸暂停患者床头抬高的影响）',
        text32: '',
        text33: '',
        text13: '',
        text14: '',
        text15: '',
        text16: '',
        text22: '',
        text23: '',
        text24: '',
        text34: '',
        text35: '',
      })
    } else if (this.data.time > 876 && this.data.time <= 931) {
      this.setData({
        title1: '',
        text1: '',
        text12: '',
        title2: '',
        text2: '',
        title3: '',
        text31: '',
        text32: '',
        text33: '',
        text13: '',
        text14: '',
        text15: '',
        text16: '',
        text22: '',
        text23: '',
        text24: '',
        text34: '',
        text35: '',
      })
    }
  },

  close: function () {
    this.setData({
      fixedExplainFlag: false
    })
  },

  fixedExplain2: function () {
    this.setData({
      fixedExplainFlag: true,
      title1: '实时数据',
      text1: '   实时展示一键入眠期间心率、呼吸率数据变化，对自身体征数据一目了然。',
      text12: '',
      title2: '',
      text2: '',
      title3: '为什么部分时段无实时数据？',
      text31: '　　舒福德智能床采用羽感级力学传感器，采集身体产生的机械振动信号（呼吸波动信号、由心脏脉冲引起的BCG信号等），并通过专业算法分析得到并展示体征数据。',
      text32: '　　当智能床处于按摩放松时段时产生的振动，会导致传感器采集到错误的机械振动信号，无法显示实时数据。当处于非按摩放松时段时，实时数据即可正常显示。',
      text33: '',
      text13: '',
      text14: '',
      text15: '',
      text16: '',
      text22: '',
      text23: '',
      text24: '',
      text34: '',
      text35: '',
    })
  },

  closeReport() {
    this.setData({
      reportSuccessFlag: false
    })
    this.bingLongTap()
  },
  closeReport2() {
    this.setData({
      dialogShow2: false
    })
    this.bingLongTap()
  },
  toReport() {
    const _this = this
    this.setData({
      reportSuccessFlag: false
    })
    this.setData({
      time: 0,
      explain1: '深度放松 释放压力 快速入眠',
      explain2: '助眠过程中操作遥控器任意按钮都会打断一键入眠',
      level: 1,
      functionFlag: false,
      title1: '',
      text1: '',
      text12: '',
      title2: '',
      text2: '',
      title3: '',
      text31: '',
      text32: '',
      text33: '',
      showProgress: false,
      text13: '',
      text14: '',
      text15: '',
      text16: '',
      text22: '',
      text23: '',
      text24: '',
      text34: '',
      text35: '',
    })
    this.setData({
      heartRate: '--',
      breathRate: '--',
      noData: true
    })
    wx.setStorageSync('oneManSleep', null)
    // app.globalData.playmusic.stop()
    _this.drawProgressCircle(0);
    clearTimeout(timer)
    clearTimeout(timer2)
    app.globalData.BRDATA = []
    app.globalData.HRDATA = []
    app.globalData.setBR = []
    app.globalData.setHR = []
    wx.offBLECharacteristicValueChange(_this.data.listener)
    wx.redirectTo({
      url: '/pages/index/oneButtonSleep/stressReport/stressreport?stressdata=' + _this.data.stressData,
    })
  },
  dialogHandle2: function (e) {
    this.setData({
      dialogShow2: e.detail.params
    })
  },
  //重新进入页面时重绘进度
  reDraw() {
    let _this = this
    let temp = wx.getStorageSync('oneManSleep')
    console.log('temp===>', temp, app.globalData.setHR, app.globalData.setBR)
    if (temp != null && temp != undefined) {
      this.setData({
        functionFlag: true,
        showProgress: true,
        noData: false,
        hr: app.globalData.HRDATA,
        br: app.globalData.BRDATA,
        setHR: app.globalData.setHR,
        setBR: app.globalData.setBR
      })
      temp = parseInt(temp)
      var myDate = new Date();
      let time = _this.timedifference(new Date(temp), myDate.getTime())
      _this.setData({
        time: time
      })
      _this.oneComponent = _this.selectComponent('#mychart-dom-bar');
      this.reRender()
      if (this.data.functionFlag == false || time > 931) {
        _this.setData({
          level: 1,
          time: 0,
          explain1: '深度放松 释放压力 快速入眠',
          explain2: '助眠过程中操作遥控器任意按钮都会打断一键入眠',
          functionFlag: false
        })
        _this.drawProgressCircle(0);
      } else if (time > 0 && time <= 25 && _this.data.explain2 != '零重力减压，太空失重体验，释放身体压力') {
        _this.setData({
          level: 1,
          explain1: '全身舒展中',
          explain2: '零重力减压，太空失重体验，释放身体压力',
        })
        _this.time(new Date(temp))
        _this.drawProgressCircle(time / 931);
      } else if (time > 25 && time <= 80 && _this.data.explain2 != '零重力按摩，头部深度按摩，消除疲劳') {
        _this.setData({
          level: 1,
          explain1: '全身舒展中',
          explain2: '零重力按摩，头部深度按摩，消除疲劳',
        })
        _this.time(new Date(temp))
        _this.drawProgressCircle(time / 931);
      } else if (time > 80 && time <= 146 && _this.data.explain2 != '摇摆哄睡，全身舒展') {
        _this.setData({
          level: 1,
          explain1: '全身舒展中',
          explain2: '摇摆哄睡，全身舒展',
        })
        _this.time(new Date(temp))
        _this.drawProgressCircle(time / 931);
      } else if (time > 146 && time <= 326 && _this.data.explain2 != '振动按摩，全身按摩减压') {
        _this.setData({
          level: 2,
          explain1: '全身放松中',
          explain2: '振动按摩，全身按摩减压',
        })
        _this.time(new Date(temp))
        _this.drawProgressCircle(time / 931);
      } else if (time > 326 && time <= 481 && _this.data.explain2 != '促进呼吸，足部放松') {
        _this.setData({
          level: 2,
          explain1: '全身放松中',
          explain2: '促进呼吸，足部放松',
        })
        _this.time(new Date(temp))
        _this.drawProgressCircle(time / 931);
      } else if (time > 481 && time <= 676 && _this.data.explain2 != '零重力拉伸，全身放松') {
        _this.setData({
          level: 3,
          explain1: '体位入眠中',
          explain2: '零重力拉伸，全身放松',
        })
        _this.time(new Date(temp))
        _this.drawProgressCircle(time / 931);
      } else if (time > 676 && time <= 876 && _this.data.explain2 != '促进呼吸，体位入眠') {
        _this.setData({
          level: 3,
          explain1: '体位入眠中',
          explain2: '促进呼吸，体位入眠',
        })
        _this.time(new Date(temp))
        _this.drawProgressCircle(time / 931);
      } else if (time > 876 && time <= 931 && _this.data.explain2 != '晚安好梦') {
        _this.setData({
          level: 3,
          explain1: '体位入眠中',
          explain2: '晚安好梦',
        })
        _this.time(new Date(temp))
        _this.drawProgressCircle(time / 931);
      } else {
        _this.time(new Date(temp))
        _this.drawProgressCircle(time / 931);
      }
    } else {
      this.drawProgressCircle(0);
    }
  },
  //图表及实时数据重新渲染
  reRender() {
    let _this = this
    let HR = app.globalData.setHR
    let BR = app.globalData.setBR
    if (this.data.functionFlag != false) {
      this.init_chart(app.globalData.BRDATA, app.globalData.HRDATA)
      if (HR && BR) {
        if (HR.length >= 1 && BR.length >= 1) {
          _this.setData({
            heartRate: HR[HR.length - 1],
            breathRate: BR[BR.length - 1]
          })
        }
      }
      setTimeout(() => {
        _this.reRender()
      }, 10000);
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  setmusic() {
    let zeroSign = ''
    if (wx.getStorageSync('songNow') < 9) {
      zeroSign = '0'
    } else {
      zeroSign = ''
    }
    this.setData({
      musicClassName: wx.getStorageSync('songArrayNow')[wx.getStorageSync('songNow')].secondTypeName,
      musicName: zeroSign + (wx.getStorageSync('songNow') - 1 + 2) + '.' + wx.getStorageSync('songArrayNow')[wx.getStorageSync('songNow')].name,
      musicTimeLong: wx.getStorageSync('songArrayNow')[wx.getStorageSync('songNow')].time
    })
    if (wx.getStorageSync('songArrayNow')[wx.getStorageSync('songNow')].secondTypeName == '雨') {
      this.setData({
        songBackground: 'https://ks-experience-system.oss-cn-hangzhou.aliyuncs.com/softide/version_2/experience/mainRain.png'
      })
    } else if (wx.getStorageSync('songArrayNow')[wx.getStorageSync('songNow')].secondTypeName == '虫鸣') {
      this.setData({
        songBackground: 'https://ks-experience-system.oss-cn-hangzhou.aliyuncs.com/softide/version_2/experience/mainInsectsCry.png'
      })
    } else if (wx.getStorageSync('songArrayNow')[wx.getStorageSync('songNow')].secondTypeName == '野外') {
      this.setData({
        songBackground: 'https://ks-experience-system.oss-cn-hangzhou.aliyuncs.com/softide/version_2/experience/mainGround.png'
      })
    } else if (wx.getStorageSync('songArrayNow')[wx.getStorageSync('songNow')].secondTypeName == '脚步') {
      this.setData({
        songBackground: 'https://ks-experience-system.oss-cn-hangzhou.aliyuncs.com/softide/version_2/experience/mainFoot.png'
      })
    } else if (wx.getStorageSync('songArrayNow')[wx.getStorageSync('songNow')].secondTypeName == '流水') {
      this.setData({
        songBackground: 'https://ks-experience-system.oss-cn-hangzhou.aliyuncs.com/softide/version_2/experience/mainWater.png'
      })
    } else if (wx.getStorageSync('songArrayNow')[wx.getStorageSync('songNow')].secondTypeName == '海浪') {
      this.setData({
        songBackground: 'https://ks-experience-system.oss-cn-hangzhou.aliyuncs.com/softide/version_2/experience/mainSea.png'
      })
    } else if (wx.getStorageSync('songArrayNow')[wx.getStorageSync('songNow')].secondTypeName == '轻快') {
      this.setData({
        songBackground: 'https://ks-experience-system.oss-cn-hangzhou.aliyuncs.com/softide/version_2/experience/mainFast.png'
      })
    } else if (wx.getStorageSync('songArrayNow')[wx.getStorageSync('songNow')].secondTypeName == '冥想') {
      this.setData({
        songBackground: 'https://ks-experience-system.oss-cn-hangzhou.aliyuncs.com/softide/version_2/experience/mainThink.png'
      })
    } else if (wx.getStorageSync('songArrayNow')[wx.getStorageSync('songNow')].secondTypeName == '旋律') {
      this.setData({
        songBackground: 'https://ks-experience-system.oss-cn-hangzhou.aliyuncs.com/softide/version_2/experience/mainSong.png'
      })
    }
  },
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    let temp = wx.getStorageSync('smartRelax')
    if (temp != null && temp != undefined) {
      clearTimeout(timer)
      clearTimeout(timer2)
      app.globalData.BRDATA = null
      app.globalData.HRDATA = null
      app.globalData.setBR = null
      app.globalData.setHR = null
    }
    this.reDraw()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {
    clearTimeout(timer)
    // let _this = this
    // wx.offBLECharacteristicValueChange(_this.data.listener)
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    clearTimeout(timer)
    // let _this = this
    // wx.offBLECharacteristicValueChange(_this.data.listener)
    // if (this.data.functionFlag == true) {
    //   this.bedToStop()
    //   setTimeout(() => {
    //     _this.bedToFlat()
    //   }, 200);
    //   this.setData({
    //     functionFlag: false,
    //   })
    // }
    // setTimeout(() => {
    // 	let closeCon = utils.closeBLEConnection(_this.data.deviceID);
    // }, 300);
    // app.globalData.playmusic.stop()
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },

  //倒计时方法
  // countInterval: function () {
  //   // 设置倒计时 定时器 每100毫秒执行一次，计数器count+1 ,耗时6秒绘一圈
  //   this.countTimer = setInterval(() => {
  //     if (this.data.count <= 60) {
  //       /* 绘制彩色圆环进度条  
  //       注意此处 传参 step 取值范围是0到2，
  //       所以 计数器 最大值 60 对应 2 做处理，计数器count=60的时候step=2
  //       */
  //       this.drawProgressCircle(this.data.count / (120 / 2));
  //       this.data.count++
  //     } else {
  //       clearInterval(this.countTimer);
  //     }
  //   }, 1000)
  // },
  /**
   * 绘制灰色背景
   */
  drawProgressbg: function () {
    // 使用 wx.createContext 获取绘图上下文 context
    var ctx = null;
    wx.createSelectorQuery()
      .select("#canvasProgressbg")
      .context(function (res) {
        // console.log("节点实例：", res);
        // 节点对应的 Canvas 实例。
        ctx = res.context;
        ctx.setLineWidth(30); // 设置圆环的宽度
        ctx.setStrokeStyle('#79E5FF'); // 设置圆环的颜色
        ctx.setLineCap('round') // 设置圆环端点的形状
        ctx.beginPath(); //开始一个新的路径
        ctx.arc(150, 151, 135, -Math.PI, 0, false);
        //设置一个原点(110,110)，半径为100的圆的路径到当前路径
        ctx.stroke(); //对当前路径进行描边
        ctx.draw();
      })
      .exec();


  },
  /**
   * 绘制小程序进度
   * @param {*} step 
   */
  drawProgressCircle: function (step) {
    //   console.log(this.data.goMusic)
    if (this.data.showProgress == true && this.data.functionFlag == true && this.data.goMusic == false) {
      let ctx = null;
      wx.createSelectorQuery()
        .select("#canvasProgress")
        .context(function (res) {
          // console.log("节点实例：", res); // 节点对应的 Canvas 实例。
          ctx = res.context;
          // 设置渐变
          var gradient = ctx.createLinearGradient(200, 100, 100, 200);
          // gradient.addColorStop("0", "#2661DD");
          // gradient.addColorStop("0.5", "#2661DD");
          // gradient.addColorStop("1.0", "#2661DD");
          ctx.setLineWidth(30);
          // ctx.setStrokeStyle(gradient);
          ctx.setStrokeStyle('#1EC6FF'); // 设置圆环的颜色
          ctx.setLineCap('round')
          ctx.beginPath();
          // 参数step 为绘制的圆环周长，从0到2为一周 。 -Math.PI / 2 将起始角设在12点钟位置 ，结束角 通过改变 step 的值确定
          ctx.arc(150, 151, 135, -Math.PI, step * Math.PI - Math.PI, false);
          ctx.stroke();
          ctx.draw()
        })
        .exec();
    }
  },

  sendMsgAgain: async function (msg) {
    console.log("success sendMsgAgain:", res);
    let sendResult = await bluetoothUtils.sendMsg(msg);
    if (sendResult) {
      resolve(sendResult);
    } else {
      resolve();
    }
  },

  //开启一键入眠
  startOneButtonSleep: async function () {
    let _this = this;
    // let sendmessageRes = await this.sendMsg("E6FE160800000000FD");
    //先打断0.6s后发送指令
    app.globalData.playmusic = wx.getBackgroundAudioManager()
    app.globalData.playmusic.stop()
    let sendmessageRes0 = await bluetoothUtils.sendMsg("AA03000A00040100000002F8F355");
    await bluetoothUtils.wait(0.6)
    let sendmessageRes1 = await bluetoothUtils.sendMsg("AA03000A00040100000002F8F355");
    await bluetoothUtils.wait(0.6)
    let sendmessageRes = await bluetoothUtils.sendMsg("AA0C001000100A00000040030100000000A1E455");
    if (!sendmessageRes) {
      bluetoothUtils.myShowToast("蓝牙连接中断");
    }
    utils.insertRemoteKey(app.globalData.deviceId, 'one_key_sleep', "AA0C001000100A00000040030100000000A1E455")
    // let data = {
    //   device_id: app.globalData.deviceId,
    //   scene_key: 'one_key_sleep'
    // }
    // api.setBedControl(data, app.globalData.token).then(res => {
    //   if (res.data.code == 200) {
    //     console.log('开启一键入眠成功')
    //   } else {
    //     console.log('error', res.data.msg)
    //   }
    // })
  },
  // 一键放平
  bedToFlat: async function () {
    let _this = this;
    // let sendmessageRes = await this.sendMsg("E6FE160000000800FD");
    let sendmessageRes = await bluetoothUtils.sendMsg("AA03000A00040100000008F2F355");
    console.log("一键放平:", sendmessageRes);
    if (!sendmessageRes) {
      this.closeBleCon("蓝牙连接中断，请重试");
    }
  },

  //打断
  bedToStop: async function () {
    let _this = this;
    // let sendmessageRes = await this.sendMsg("E6FE160000000800FD");
    let sendmessageRes = await bluetoothUtils.sendMsg("AA03000A00040100000002F8F355");
    console.log("一键打断:", sendmessageRes);
    if (!sendmessageRes) {
      this.closeBleCon("蓝牙连接中断，请重试");
    }
  },
})

function line_set(chart_4, xdata, ydata) {
  var option_4 = {
    xAxis: {
      type: 'category',
      boundaryGap: false,
      axisTick: {
        show: false
      },
      splitLine: {
        show: false,
        lineStyle: {
          color: '#666870',
          width: 1,
          type: 'solid',
        },
      },
      axisLabel: {
        show: false,
      },
      axisLine: {
        show: false,
        axisTick: {
          show: false,
        },
        lineStyle: {
          color: '#666870 ',
          width: 1, //这里是为了突出显示加上的
        },
      },
    },
    yAxis: {
      type: 'value',
      splitLine: {
        show: true,
        lineStyle: {
          color: 'rgba(151, 151, 151, 0.2)',
          width: 2,
          type: 'dashed',
        },
      },
      axisLabel: {
        textStyle: {
          color: 'rgba(0,0,0,0.35)',
          fontFamily: 'PingFangSC-Regular, PingFang SC;',
          fontSize: '15',
        },
      },
      axisLine: {
        show: false,
        axisTick: {
          show: false,
        },
        lineStyle: {
          color: '#F2F6FE ',
          width: 1, //这里是为了突出显示加上的
        },
      },
    },
    series: [{
        smooth: true,
        symbolSize: 1, //设定实心点的大小
        data: xdata,
        type: 'line',
        symbol: "none",
        stack: 'x',
        color: 'rgba(32, 197, 150, 1)',
        areaStyle: {
          normal: {
            color: new echarts.graphic.LinearGradient(
              0, 0, 0, 1,
              [{
                  offset: 0,
                  color: 'rgba(32, 197, 150, 1)'
                },
                {
                  offset: 1,
                  color: 'rgba(32, 197, 150, 0)'
                }
              ]
            )
          }
        },
      },
      {
        smooth: true,
        symbolSize: 1, //设定实心点的大小
        symbol: "none",
        data: ydata,
        type: 'line',
        stack: 'x',
        color: 'rgba(0, 165, 205, 1)',
        areaStyle: {
          normal: {
            color: new echarts.graphic.LinearGradient(
              0, 0, 0, 1,
              [{
                  offset: 0,
                  color: 'rgba(0, 165, 205, 1)'
                },
                {
                  offset: 1,
                  color: 'rgba(0, 165, 205, 0)'
                }
              ]
            )
          }
        },
      }
    ]
  };
  chart_4.clear()
  chart_4.setOption(option_4, true);
}